package com.acc.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.acc.dao.AdminLoginDAO;
import com.acc.entity.Admin;
import com.acc.utils.JDBCTools;
/**
 * 
 * @author 朱春阳
 *
 */
public class AdminLoginDAOImpl implements AdminLoginDAO {

	@Override
	public Admin login(String adminName, String password) {
		// TODO Auto-generated method stub

		Admin admin = null;
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		String sql = "select * from ti_admin where adminName=? and password=?";
		try {
			con = JDBCTools.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, adminName);
			pst.setString(2, password);
			rs = pst.executeQuery();
			while (rs.next()) {
				admin = new Admin();
				admin.setAdminname(rs.getString("adminName"));
				admin.setAdminId(rs.getInt("admin_id"));
				admin.setPassword(rs.getString("password"));
			}

			return admin;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JDBCTools.close(con, pst, rs);
		}

		return admin;
	}

	@Override
	public List<String> getAllRolesByName(String adminName) {
		// TODO Auto-generated method stub
		List<String> roles = new ArrayList<>();
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		String sql = "select * from admin_role where admin_name=?";
		try {
			con = JDBCTools.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, adminName);
			rs = pst.executeQuery();
			while (rs.next()) {
				roles.add(rs.getString("admin_role"));
			}

			return roles;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JDBCTools.close(con, pst, rs);
		}

		return roles;
	}

	@Override
	public Set<String> getAllUri(String role) {
		// TODO Auto-generated method stub
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		Set<String> uris = new HashSet<String>();
		String sql = "select uri from ti_role where role=?";
		try {
			con = JDBCTools.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, role);
			rs = pst.executeQuery();
			while (rs.next()) {
				uris.add(rs.getString("uri"));
			}

			return uris;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JDBCTools.close(con, pst, rs);
		}

		return uris;
	}

}
